#include <stdio.h>
#include <allegro5/allegro.h>
#include "allegro5/allegro_image.h"
#include "allegro5/allegro_opengl.h"
#include "world.h"

const float FPS = 60;

int main(int argc, char **arg) {

	ALLEGRO_DISPLAY *display = 0;
	ALLEGRO_EVENT_QUEUE *event_queue = 0;
	ALLEGRO_TIMER *timer = 0;
	bool redraw = true;

	if (!al_init()) {
		fprintf(stderr, "failed to initialize allegro\n");
		return -1;
	}

	// Timer
	timer = al_create_timer(1.0 /FPS);
	if (!timer) {
		fprintf(stderr, "failed to create timer\n");
		return -1;
	}

	// Display
	al_set_new_display_flags(ALLEGRO_OPENGL); 
	display = al_create_display(640, 480);
	if (!display) {
		fprintf(stderr, "failed to create display\n");
		return -1;
	}

	// Events
	event_queue = al_create_event_queue();
	if (!event_queue) {
		fprintf(stderr, "failed to create event queue\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	if(!al_init_image_addon()) {
		fprintf(stderr, "failed to init image addon\n");
		return -1;
	}

	//ALLEGRO_BITMAP *b = al_create_bitmap(32, 32);
	/*ALLEGRO_BITMAP *b = al_load_bitmap("dd_logo.png");
	if (!b) {
		fprintf(stderr, "failed to load bitmap\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}
	*/

	al_register_event_source(event_queue, al_get_display_event_source(display));
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_clear_to_color(al_map_rgb(0, 0, 0));
	al_flip_display();
	al_start_timer(timer);

	glMatrixMode(GL_PROJECTION); //Open the projection matrix as current
	glLoadIdentity(); //clear its contents to an identity matrix (which doesn't change anything when applied)
	//gluPerspective( 45.0f, 16/9.0f, 1.0f, 100.0f);
	glOrtho(-10, 10, -10, 10, 1, 100);

	glMatrixMode(GL_MODELVIEW); //select the matrix
	glLoadIdentity();

	float v[] = {0, 0, 0, -1, -1, 0, 1, -1, 0};

	struct world *w = malloc(sizeof(struct world));
	avgdl_world_init(w);

	// Game loop
	while (1) {
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_TIMER) {
			redraw = true;
		}
		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}

		glLoadIdentity();
		glTranslatef(0, 0, -2);

		/*
		glBegin(GL_LINES);
		glVertex3f(0,0,0);
		glVertex3f(30,30,30); 
		glEnd();

		glEnableClientState(GL_VERTEX_ARRAY);
		glVertexPointer(3, GL_FLOAT, 0, v);
		glDrawArrays(GL_TRIANGLES, 0, 9);
		glDisableClientState(GL_VERTEX_ARRAY);
		*/

		avgdl_world_draw(w);

		al_flip_display();

		/*
		if (redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;
			al_clear_to_color(al_map_rgb(255, 0, 0));
			al_draw_bitmap(b, 0, 0, 0);
		}
		*/
	}

	//al_destroy_bitmap(b);
	al_destroy_timer(timer);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);

	return 0;
}
